package com.lyy.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 抖音的相关工具类
 */
public class TikTokUtils {
    /**
     * 此接口可以下载抖音的无水印的视频和图片
     *
     * @param linkUrl
     * @param targetSavePath
     * @param type 文件类型：pic图片  mp3音乐  video视频
     * @return
     * @throws Exception
     */
    public static void tikTokPicDownload(String linkUrl,String targetSavePath,String type) throws Exception {
        List<String> finalPaths=new ArrayList<>();
        //①：过滤视频得到http链接地址
        String finalUrl = decodeHttpUrl(linkUrl);
        final String videoPath = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=";
        Connection con = Jsoup.connect(finalUrl);
        con.header("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
        Connection.Response resp = con.method(Connection.Method.GET).execute();
        String strUrl = resp.url().toString();
        String itemId = strUrl.substring(strUrl.indexOf("video/"), strUrl.lastIndexOf("/")).replace("video/", "");
        String videoUrl = videoPath + itemId;
        String jsonStr = Jsoup.connect(videoUrl).ignoreContentType(true).execute().body();
        JSONObject json = new JSONObject(jsonStr);
        if(type.contains("pic")){
            JSONArray picArr = json.getJSONArray("item_list").getJSONObject(0).getJSONArray("images");
            if(picArr!=null&&picArr.size()>0){
                for(int i=0;i<picArr.size();i++){
                    String url_list = picArr.getJSONObject(i).getJSONArray("url_list").get(0).toString();
                    finalPaths.add(url_list);
                }
            }
        }
        else if(type.contains("mp3")){
            String mp3Address = json.getJSONArray("item_list").getJSONObject(0).getJSONObject("video")
                    .getJSONObject("play_addr").get("uri").toString();
            finalPaths.add(mp3Address);
        }
        else if(type.contains("video")){
            String videoAddress = json.getJSONArray("item_list").getJSONObject(0).getJSONObject("video").getJSONObject("play_addr")
                    .getJSONArray("url_list").get(0).toString();
            HashMap headers = MapUtil.newHashMap();
            headers.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
            String replace = videoAddress.replace("playwm", "play"); //替换成无水印链接
            HttpResponse execute = HttpUtil.createGet(replace).addHeaders(headers).execute();
            String finalVideoAddress = execute.header("Location");
            finalPaths.add(finalVideoAddress);
        }
        if(finalPaths.size()>0) {
            for(String finalPath:finalPaths) {
                downloadVideo(finalPath, targetSavePath,type);
            }
        }
    }

    /**
     * 过滤视频得到http链接地址
     *
     * @param url
     * @return
     */
    private static String decodeHttpUrl(String url) {
        int start = url.indexOf("http");
        int end = url.lastIndexOf("/");
        return url.substring(start, end);
    }

    /**
     * 下载
     *
     * @param videoAddress  下载文件的输入流地址
     * @param targetSavePath 保存的本路文件夹的路径
     */
    private static void downloadVideo(String videoAddress,String targetSavePath,String type) {
        int byteRead;
        try {
            URL url = new URL(videoAddress);
            //获取链接
            URLConnection conn = url.openConnection();
            //输入流
            InputStream inStream = conn.getInputStream();
            String target="";
            if(type.contains("pic")){
                target=targetSavePath + File.separatorChar +System.currentTimeMillis() + ".jpg";
            }else if(type.contains("mp3")){
                target=targetSavePath + File.separatorChar +System.currentTimeMillis() + ".mp3";
            }else if(type.contains("video")){
                target=targetSavePath + File.separatorChar +System.currentTimeMillis() + ".mp4";
            }
            //封装一个保存文件的路径对象
            File fileSavePath = new File(target);
            //注:如果保存文件夹不存在,那么则创建该文件夹
            File fileParent = fileSavePath.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            if (fileSavePath.exists()) { //如果文件存在，则删除原来的文件
                fileSavePath.delete();
            }
            //写入文件
            FileUtils.write(target,inStream);
            inStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
